package com.hello.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.dto.CommentsDTO;
import com.hello.dto.PostSearchDTO;
import com.hello.dto.UserCommentsDTO;
import com.hello.entity.Comments;
import com.hello.entity.Post;
import com.hello.entity.User;
import com.hello.mapper.CommentsMapper;
import com.hello.service.ICommentsService;
import com.hello.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements ICommentsService {
    @Autowired
    private IUserService userService;

    @Override
    public List<Comments> getComments(Long user_id){
        QueryWrapper<Comments> wrapper = new QueryWrapper<Comments>()
                .select("*")
                .eq("host_id",user_id);
        List<Comments> comments = baseMapper.selectList(wrapper);
        return comments;

    }
    @Override
    public Long getCommentCount(Long user_id,Integer post_order){
        QueryWrapper<Comments> wrapper = new QueryWrapper<Comments>()
                .select("*")
                .eq("host_id",user_id)
                .eq("post_order",post_order);
        Long count = baseMapper.selectCount(wrapper);
        return count;

    }
    @Override
    public List<UserCommentsDTO> postComments(PostSearchDTO postSearchDTO){
        QueryWrapper<Comments> wrapper = new QueryWrapper<Comments>()
                .select("*")
                .eq("host_id",postSearchDTO.getHostId())
                .eq("post_order",postSearchDTO.getPostOrder());
        List<Comments> commentsList = baseMapper.selectList(wrapper);

        List<UserCommentsDTO> userCommentsDTO = new ArrayList<>();
        for (Comments comments : commentsList) {
            UserCommentsDTO commentsDTO = new UserCommentsDTO();
            BeanUtils.copyProperties(comments, commentsDTO);
            userCommentsDTO.add(commentsDTO);
        }


        return userCommentsDTO;
    }
    @Override
    public boolean addComment(CommentsDTO commentsDTO){
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentsDTO,comments);
        comments.setCommentTime(LocalDateTime.now());
        Integer maxCommentOrder = baseMapper.getMaxCommentOrder();
        comments.setCommentOrder(maxCommentOrder!=null?maxCommentOrder+1:1);

        int num = baseMapper.insert(comments);
        return num>0?true:false;
    }


//    @Override
//    public String getuserName(UserCommentsDTO userCommentsDTO){
//        String username = userService.get .getUsername(userCommentsDTO.getHostId());
//        return username;
//    }
}
